/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.gitee.minimalismstyle.fresh.simple.service.impl

import com.alibaba.druid.pool.DruidDataSource
import com.gitee.minimalismstyle.fresh.common.core.extra.toPropety
import com.gitee.minimalismstyle.fresh.common.data.beetl.service.impl.LongModelBaseServiceImpl
import com.gitee.minimalismstyle.fresh.simple.dao.SimpleDatasourceDao
import com.gitee.minimalismstyle.fresh.simple.api.model.SimpleDatasource
import com.gitee.minimalismstyle.fresh.simple.api.service.SimpleDatasourceService
import org.beetl.sql.core.ConnectionSource
import org.beetl.sql.ext.spring.SpringConnectionSource
import org.springframework.context.annotation.Primary
import org.springframework.stereotype.Service

/**
 * 数据源业务实现
 * @author maoxiaodong
*/
@Primary
@Service
class SimpleDatasourceServiceImpl: SimpleDatasourceService, LongModelBaseServiceImpl<SimpleDatasourceDao, SimpleDatasource>(){
    override fun getConnectionSource(datasourceId: Long): ConnectionSource {
        val simpleDatasource = dao.findById(datasourceId)
        val datasource: DruidDataSource = if (DATASOURCES.containsKey(simpleDatasource.id)) {
            DATASOURCES[simpleDatasource.id]!!
        } else {
            newDruidDataSource(simpleDatasource)
        }
        val connectionSource = SpringConnectionSource()
        connectionSource.masterSource = datasource
        return connectionSource
    }

    @Synchronized
    private fun newDruidDataSource(simpleDatasource: SimpleDatasource): DruidDataSource {
        val datasource = DruidDataSource()
        datasource.configFromPropety(simpleDatasource.params!!.toPropety("druid"))
        DATASOURCES[simpleDatasource.id!!] = datasource
        return datasource
    }

    companion object {
        val DATASOURCES = hashMapOf<Long, DruidDataSource>()
    }
}